#!/usr/bin/env python
# Last Change: 2010-03-16 22:35:19

import re

urlre = re.compile('^([^:]+):((?://)?)(?:(\w+)(?::(\w+))?@)?([^/]*)(/[^?]*)?(?:\?([^#]+))?(?:#(.+))?$')

class url(object):

  def __init__(self, **kw):
    self.scheme = kw['scheme'] or ''
    self.absolute = kw['absolute'] or ''
    self.user = kw['user'] or ''
    self.password = kw['password'] or ''
    self.host = kw['host'] or ''
    self.path = kw['path'] or ''
    self.query = kw['query'] or ''
    self.fragment = kw['fragment'] or ''

  def __add__(self, sub):
    if not self.path.endswith('/'):
      self.path += '/'
    self.path += sub
    return self

  def __str__(self):
    return repr(self)

  def __repr__(self):
    buf = self.scheme
    buf += ':'
    if self.absolute:
      buf += '//'
    if self.user:
      buf += self.user
      if self.password:
        buf += ':'
        buf += self.password
      buf += '@'
    buf += self.host
    buf += self.path
    if self.query:
      buf += '?'
      buf += self.query
    if self.fragment:
      buf += '#'
      buf += self.fragment
    return buf


def urlparse(string):
  m = re.match(urlre, string)
  if m:
    return url(scheme=m.group(1), absolute=m.group(2), user=m.group(3), password=m.group(4),
        host=m.group(5), path=m.group(6), query=m.group(7), fragment=m.group(8)) 

if __name__ == '__main__':
  urlhttp = 'http://name:pass@www.host.net/page?arg=param#tag'
  u = urlparse(urlhttp)
  assert(u.scheme == 'http')
  assert(u.absolute)
  assert(u.user == 'name')
  assert(u.password == 'pass')
  assert(u.host == 'www.host.net')
  assert(u.path == '/page')
  assert(u.query == 'arg=param')
  assert(u.fragment == 'tag')
  assert(u.__str__() == urlhttp)

  urlmailto = 'mailto:name@mail.host.net'
  u = urlparse(urlmailto)
  assert(u .scheme == 'mailto')
  assert(not u.absolute)
  assert(u.user == 'name')
  assert(not u.password)
  assert(u.host == 'mail.host.net')
  assert(not u.path)
  assert(not u.query)
  assert(not u.fragment)
  assert(u.__str__() == urlmailto)
  
